package com.suntianci.stock.service.impl;

import com.suntianci.stock.constant.PermissionConstant;
import com.suntianci.stock.mapper.SysPermissionMapper;
import com.suntianci.stock.mapper.SysRolePermissionMapper;
import com.suntianci.stock.pojo.domain.PermissionDomain;
import com.suntianci.stock.pojo.domain.PermissionInfo4AddPermissionDomain;
import com.suntianci.stock.pojo.entity.SysPermission;
import com.suntianci.stock.service.PermissionService;
import com.suntianci.stock.utils.IdWorker;
import com.suntianci.stock.utils.PermissionUtil;
import com.suntianci.stock.vo.req.AddPermissionReqVo;
import com.suntianci.stock.vo.req.UpdatePermissionReqVo;
import com.suntianci.stock.vo.resp.R;
import com.suntianci.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PermissionServiceImpl
 * @Author 孙天赐
 * @Date 2025/1/11 16:19
 * @Description TODO: 权限服务接口实现类
 */
@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    /**
     * 查询所有权限集合
     *
     * @return
     */
    @Override
    public R<List<SysPermission>> getAllPermission() {
        List<SysPermission> result = sysPermissionMapper.getAllPermission();
        return R.ok(result);
    }

    /**
     * 树状结构查询权限集合
     *
     * @return
     */
    @Override
    public R<List<PermissionDomain>> getAllPermission2Tree() {
        // 获取全部权限
        List<SysPermission> allPermission = sysPermissionMapper.getAllPermission();
        // 构建权限树，全部权限都要
        List<PermissionDomain> result = new ArrayList<>();
        for (SysPermission sysPermission : allPermission) {
            if (sysPermission.getPid().equals(0L)) {
                PermissionDomain permissionTree = PermissionUtil.getAllPermissionTree(sysPermission, allPermission);
                result.add(permissionTree);
            }
        }
        // 返回结果
        return R.ok(result);
    }

    /**
     * 添加权限时回显权限树,仅仅显示目录和菜单
     *
     * @return
     */
    @Override
    public R<List<PermissionInfo4AddPermissionDomain>> getAllPermissionWithLevel() {
        // 获取全部权限
        List<SysPermission> allPermission = sysPermissionMapper.getAllPermission();
        // 根据全部权限，提取权限信息及等级
        List<PermissionInfo4AddPermissionDomain> result = new ArrayList<>();
        // 第一个一定是顶级菜单
        PermissionInfo4AddPermissionDomain topMenu = PermissionInfo4AddPermissionDomain.builder()
                .id("0")
                .title("顶级菜单")
                .level(0).build();
        result.add(topMenu);
        // 获取其他权限信息
        for (SysPermission sysPermission : allPermission) {
            // 如果为1级权限
            if (sysPermission.getPid() == 0 && (sysPermission.getType() == PermissionConstant.TYPE_DIRECTORY || sysPermission.getType() == PermissionConstant.TYPE_MENU)) {
                // 获取该权限及其所有子权限的信息
                PermissionUtil.getPermissionInfoAndLevelWithDirectiryAndMenu(result, sysPermission, allPermission, 1);
            }
        }

        return R.ok(result);

    }

    /**
     * 添加权限
     *
     * @param addPermissionReqVo
     * @return
     */
    @Override
    public R<Void> addPermission(AddPermissionReqVo addPermissionReqVo) {
        // 新建对象用于添加数据
        SysPermission sysPermission = SysPermission.builder()
                .id(idWorker.nextId())
                .code(addPermissionReqVo.getCode())
                .title(addPermissionReqVo.getTitle())
                .icon(addPermissionReqVo.getIcon())
                .perms(addPermissionReqVo.getPerms())
                .url(addPermissionReqVo.getUrl())
                .method(addPermissionReqVo.getMethod())
                .name(addPermissionReqVo.getName())
                .pid(addPermissionReqVo.getPid())
                .orderNum(addPermissionReqVo.getOrderNum())
                .type(Integer.parseInt(addPermissionReqVo.getType()))
                .status(1)
                .createTime(DateTime.now().toDate())
                .deleted(1).build();
        int row = sysPermissionMapper.insertSelective(sysPermission);
        if (row > 0) {
            return R.ok(ResponseCode.SUCCESS);
        }
        return R.error(ResponseCode.ERROR);
    }

    /**
     * 修改权限信息
     * @param updatePermissionReqVo
     * @return
     */
    @Override
    public R<Void> updatePermission(UpdatePermissionReqVo updatePermissionReqVo) {
        // 新建对象用于添加数据
        SysPermission sysPermission = SysPermission.builder()
                .id(updatePermissionReqVo.getId())
                .code(updatePermissionReqVo.getCode())
                .title(updatePermissionReqVo.getTitle())
                .icon(updatePermissionReqVo.getIcon())
                .perms(updatePermissionReqVo.getPerms())
                .url(updatePermissionReqVo.getUrl())
                .method(updatePermissionReqVo.getMethod())
                .name(updatePermissionReqVo.getName())
                .pid(updatePermissionReqVo.getPid())
                .orderNum(updatePermissionReqVo.getOrderNum())
                .type(Integer.parseInt(updatePermissionReqVo.getType()))
                .updateTime(DateTime.now().toDate())
                .build();
        // 修改数据
        sysPermissionMapper.updateByPrimaryKeySelective(sysPermission);
        return R.ok(ResponseCode.SUCCESS);
    }

    /**
     * 根据权限id删除权限
     * @param permissionId
     * @return
     */
    @Override
    public R<Void> deletePermission(String permissionId) {
        // 删除权限表相应权限
        // 注意：由于权限存在依赖关系，所以删除一个权限的时候，也要递归删除其下的所有子权限
        // 先获取全部权限
        List<SysPermission> allPermission = sysPermissionMapper.getAllPermission();
        // 新建对象用于查询全部子权限
        SysPermission sysPermission = SysPermission.builder().id(Long.valueOf(permissionId)).build();
        // 获取当前权限下的全部子权限
        List<SysPermission> allSubPremission = PermissionUtil.getPermissionAndAllSubPermission(sysPermission, allPermission);
        // 使用stream流提取其中全部id
        List<Long> permissionIds = allSubPremission.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        // 批量删除这些权限
        int row = sysPermissionMapper.batchDelete(permissionIds);
        if(row > 0){
            // 注意，需要同时删除角色权限表相关信息
            sysRolePermissionMapper.batchDeleteByPermissionId(permissionIds);
            return R.ok(ResponseCode.SUCCESS);
        }
        return R.error(ResponseCode.ERROR);
    }

}
